package com.javasoft.service.WJC.impl;

import com.javasoft.dao.WJC.ExamQuestionMappingRepository;
import com.javasoft.dao.WJC.ExamRepository;
import com.javasoft.dao.WJC.PaperRuleRepository;
import com.javasoft.entity.WJC.Exam;
import com.javasoft.entity.WJC.ExamQuestionMapping;
import com.javasoft.entity.WJC.paperRuleEntity;
import com.javasoft.entity.XGX.Practice;
import com.javasoft.service.WJC._interface.ExamGeneratorService;
import com.javasoft.service.XGX.impl.PracticeImpl;
import com.javasoft.service.XGX.impl.QuestionImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service("examGeneratorService")
public class ExamGeneratorServiceImpl implements ExamGeneratorService {

    @Autowired
    private PaperRuleRepository paperRuleRepository;
    @Autowired
    private ExamQuestionMappingRepository examQuestionMappingRepository;
    @Autowired
    private QuestionImpl questionImpl;
    @Autowired
    private PracticeImpl practiceImpl;
    @Autowired
    private ExamRepository examRepository;

    public List<Practice> generateExamByPaperRuleId(Long paperRuleId) {
        paperRuleEntity paperRule = paperRuleRepository.findById(paperRuleId)
                .orElseThrow(() -> new IllegalArgumentException("找不到指定ID的试卷规则: " + paperRuleId));
        Long examId = generateExam(paperRule);
        List<ExamQuestionMapping> mappings = examQuestionMappingRepository.findByExamId(examId);

        List<Long> examQuestionIds = mappings.stream()
                .map(ExamQuestionMapping::getId)  // 将实体的 id 提取出来
                .collect(Collectors.toList());
        return practiceImpl.getPracticeListByIds(examQuestionIds);
    }

    public Long generateExam(paperRuleEntity paperRule) {
        Exam exam = new Exam();
        // 设置试卷的基本信息，如试卷名称、考试时长等，具体字段依据PaperRuleEntity而定
        exam.setExamName(paperRule.getExamName());
        exam.setStartTime(paperRule.getStartTime());
        exam.setEndTime(paperRule.getEndTime());
        exam.setTotalScore(Math.toIntExact(calculateTotalScore(paperRule)));
        exam.setSubject(paperRule.getSubject());
        Long paperRuleId = paperRule.getPaperRuleId();
        exam.setPaperRuleId(paperRuleId);
        exam.setDifRank(paperRule.getDifRank());
        examRepository.save(exam);

        // 分别处理不同题型的生成逻辑
        List<Long> singleChoiceQuestions = selectQuestions(paperRule.getNumSinChoice(),"单选题",paperRule.getSubject(),paperRule.getDifRank());
        List<Long> multipleChoiceQuestions = selectQuestions(paperRule.getNumMulChoice(),"多选题",paperRule.getSubject(),paperRule.getDifRank());
        List<Long> fill = selectQuestions(paperRule.getNumFill(),"填空题",paperRule.getSubject(),paperRule.getDifRank());
        List<Long> Sub = selectQuestions(paperRule.getNumSub(),"主观题",paperRule.getSubject(),paperRule.getDifRank());
        // 将选中的题目加入试卷
        for (Long id : singleChoiceQuestions) {
            saveExamQuestionMapping(exam.getExamId(), id, paperRuleId);
        }
        for (Long id : multipleChoiceQuestions) {
            saveExamQuestionMapping(exam.getExamId(), id, paperRuleId);
        }
        for (Long id : fill) {
            saveExamQuestionMapping(exam.getExamId(), id, paperRuleId);
        }
        for(Long id : Sub){
            saveExamQuestionMapping(exam.getExamId(), id, paperRuleId);
        }

        return exam.getExamId();
    }

    public void saveExamQuestionMapping(Long examId, Long id ,Long PaperRuleId) {
        ExamQuestionMapping mapping = new ExamQuestionMapping();
        mapping.setExamId(examId);
        mapping.setId(id);
        mapping.setPaperRuleId(PaperRuleId);
        examQuestionMappingRepository.save(mapping);
    }

    public List<Long> selectQuestions(int quantity, String type, String subject ,Integer difRank) {
        // 确保题目类型和科目不为空
        if (type == null || subject == null) {
            throw new IllegalArgumentException("题目类型和科目不能为空");
        }

        // 查询指定类型和科目的所有题目ID
        List<Long> allQuestionsOfTypeAndSubject = questionImpl.getQuestionsByTypeSubject(type, subject ,difRank);

        if (allQuestionsOfTypeAndSubject == null || allQuestionsOfTypeAndSubject.isEmpty() || allQuestionsOfTypeAndSubject.size() < quantity) {
            throw new IllegalArgumentException("没有足够的题目类型为：" + type + " 且科目为：" + subject + "，至少需要：" + quantity);
        }

        Random random = new Random();
        List<Long> selectedQuestions = new ArrayList<>();
        // 避免题目重复选择的逻辑保持不变
        for (int i = 0; i < quantity; i++) {
            int index = random.nextInt(allQuestionsOfTypeAndSubject.size());
            selectedQuestions.add(allQuestionsOfTypeAndSubject.get(index));
            allQuestionsOfTypeAndSubject.remove(index);
        }

        return selectedQuestions;
    }

    public int calculateTotalScore(paperRuleEntity paperRule) {
        return paperRule.getNumSinChoice() * paperRule.getScoreChoice()
                + paperRule.getNumMulChoice() * paperRule.getScoreChoice()
                + paperRule.getNumFill() * paperRule.getScoreFill()
                + paperRule.getNumSub() * paperRule.getScoreSub();
    }

}
